import numpy as np
import matplotlib.pyplot as plt

# 中文和负号正常显示
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

# 定义函数
def f(x):
    return x**2

# 生成x值
x = np.linspace(-2, 2, 100)
y = f(x)

# 在x=0.5处画切线
tangent_x = 0.5
tangent_slope = 2 * tangent_x  # 导数为2x
tangent_line = tangent_slope * (x - tangent_x) + f(tangent_x)

plt.figure(figsize=(10, 6))
plt.plot(x, y, label='y = x^2', linewidth=2)
plt.plot(x, tangent_line, '--', label=f'在x={tangent_x}处的切线', alpha=0.7)
plt.scatter([tangent_x], [f(tangent_x)], color='red', s=100, zorder=5)
plt.xlabel('x')
plt.ylabel('y')
plt.title('二次函数的凸性演示')
plt.legend()
plt.grid(True, alpha=0.3)
plt.show()